package com.yuerlive.rainbow.module.web;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.view.View;
import android.webkit.DownloadListener;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.yuerlive.rainbow.R;
import com.yuerlive.rainbow.base.BaseActivity;
import com.yuerlive.rainbow.entity.ShareInfo;
import com.yuerlive.rainbow.entity.User;
import com.yuerlive.rainbow.utils.L;
import com.yuerlive.rainbow.utils.ShareUtils;
import com.yuerlive.rainbow.utils.UserProxy;
import com.yuerlive.rainbow.widget.ShareDialog;

import butterknife.BindView;

/**
 * Created by admin on 2016/9/13.
 */
public class WebViewActivity extends BaseActivity implements View.OnClickListener, UserProxy.OnUserChangeListener {
    @BindView(R.id.subWebview)
    WebView webView;
    @BindView(R.id.progress)
    ProgressBar progressBar;
    private String url;

    private String title;
    private boolean showShare;
    private final int CODE_LOGIN = 0X998;
    public ValueCallback<Uri[]> mUploadMessageForAndroid5;
    public final static int FILECHOOSER_RESULTCODE_FOR_ANDROID_5 = 2;
    public final static int FILECHOOSER_RESULTCODE = 1;
    public ValueCallback<Uri> mUploadMessage;
    private String shareImageUrl;
    private String shareDescription;
    private String shareTitle;
    private String shareUrl;
    private ShareInfo info;

    private final static String ACTION_REFLECT = "cash/signup";
    private ShareDialog shareDialog;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_webview_layout;
    }

    @Override
    protected void initViews() {
        L.e(TAG,"initViews");
        initView();
        loadWebView(url);
    }

    @Override
    protected void onResume() {
        super.onResume();
        L.e(TAG,"onResume");
    }

    private void initView() {
        url = getIntent().getStringExtra("url");
        L.e(TAG,"initViews111111"+url);
        if (url == null)return;
        L.e(TAG,"initViews22222222");
        if (UserProxy.getUser() != null) {
            if (url.contains("?")) {
                url = url + "&";
            } else {
                url = url + "?";
            }
            url = url + "token=" + UserProxy.getUser().getToken() + "&userId=" + UserProxy.getUser().getUserId();
        }
        showShare = getIntent().getBooleanExtra("share", true);
        shareUrl = getIntent().getStringExtra("imgUrl");
        L.e(TAG,"initViews22222222"+showShare+":::"+shareUrl);
    }


    private void loadWebView(String url) {
        if (url == null) return;
        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (url.startsWith("http:") || url.startsWith("https:")) {
                    view.loadUrl(url);
                    return true;
                } else {
                    L.e(TAG,"setWebViewClient   else"+url);
                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    //TODO 不知道什么导致的异常 做的临时处理   待具体处理方式
                    try {
                        startActivity(intent);
                    } catch (Exception e) {
                        L.e(TAG, "error message" + e.getMessage());
                    }
                    return true;
                }
            }
        });
        if (!url.endsWith("activity/recruit")) {
            try {
                webSettings.setUserAgentString(webSettings.getUserAgentString() + " YuertvBrowser/" + getPackageManager().getPackageInfo(getPackageName(), 0).versionName);
            } catch (PackageManager.NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        webView.setDownloadListener(new DownloadListener() {

            @Override
            public void onDownloadStart(String url, String userAgent,
                                        String contentDisposition, String mimetype,
                                        long contentLength) {
                Uri uri = Uri.parse(url);
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        webView.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onReceivedTitle(WebView view, String title) {
                // TODO Auto-generated method stub
                super.onReceivedTitle(view, title);
                setTitle(title);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg) {
                openFileChooserImpl(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                openFileChooserImpl(uploadMsg);
            }

            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                openFileChooserImpl(uploadMsg);
            }

            @Override
            public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
                openFileChooserImplForAndroid5(filePathCallback);
                return true;
            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    // 网页加载完成
                    if (progressBar==null)return;
                    progressBar.setVisibility(View.GONE);
                } else {
                    // 加载中
                    if (progressBar != null) {
                        progressBar.setVisibility(View.VISIBLE);
                        progressBar.setProgress(newProgress);
                    }
                }
                super.onProgressChanged(view, newProgress);
            }
        });
//       webView.loadUrl("http://172.16.3.139:8080/cec"); // 加载指定网址
        webView.loadUrl(url);
        L.e(TAG,"initViews444444444444444"+url);
  //     webView.loadUrl("file:///android_asset/test.html");

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.llSina:
                ShareUtils.shareToUrl(mActivity, SHARE_MEDIA.SINA, info);
                shareDialog.dismiss();
                break;
            case R.id.llWeChat:
                ShareUtils.shareToUrl(mActivity, SHARE_MEDIA.WEIXIN, info);
                shareDialog.dismiss();
                break;
            case R.id.llFriend:
                ShareUtils.shareToUrl(mActivity, SHARE_MEDIA.WEIXIN_CIRCLE, info);
                shareDialog.dismiss();
                break;
            case R.id.llQQ:
                if (!((WebViewActivity) mActivity).checkPermissions(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE})) {
                    ((WebViewActivity) mActivity).requestPermission(new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 0x0002);
                    return;
                }
                ShareUtils.shareToUrl(mActivity, SHARE_MEDIA.QQ, info);
                shareDialog.dismiss();
                break;
        }
    }

    private void openFileChooserImpl(ValueCallback<Uri> uploadMsg) {
        L.e(TAG,"openFileChooserImpl");
        mUploadMessage = uploadMsg;
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "File Chooser"), FILECHOOSER_RESULTCODE);
    }

    private void openFileChooserImplForAndroid5(ValueCallback<Uri[]> uploadMsg) {
        L.e(TAG,"openFileChooserImplForAndroid5");
        mUploadMessageForAndroid5 = uploadMsg;
        Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
        contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
        contentSelectionIntent.setType("image/*");

        Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
        chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
        chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser");

        startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE_FOR_ANDROID_5);
    }

    @Override
    protected void onStop() {
        super.onStop();
        L.e(TAG,"onStop");
//        if (webView != null) {
//            webView.reload();
//        }
     //   UserProxy.removeListener(this);
        if(shareDialog!=null && shareDialog.isShowing()){
            shareDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        L.e(TAG,"onDestroy");

    }
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        L.e(TAG,"0000000000000000000000000000000000000000000000");
        if (intent == null || intent.getData() == null)
            return;
       if("rainbowopen".equals(intent.getData().getScheme()) && "back".equals(intent.getData().getHost())){
       L.e(TAG,"11111111111111111111111111111111111111");
       } else if ("share".equals(intent.getData().getHost()) && "rainbowopen".equals(intent.getData().getScheme())) {

          shareTitle = intent.getData().getQueryParameter("shareTitle");
          shareDescription = intent.getData().getQueryParameter("shareDescription");
          shareUrl = intent.getData().getQueryParameter("shareUrl");
          shareImageUrl = intent.getData().getQueryParameter("shareImageUrl");
           L.e(TAG,"3"+shareTitle+":::"+shareDescription+":::"+shareUrl+":::"+shareImageUrl);
          info = new ShareInfo();
          info.setWebUrl(shareUrl);
          info.setContent(shareDescription);
          info.setTitle(shareTitle);
           info.setShareImageUrl(shareImageUrl);
          info.setThumb(R.drawable.default_img);
           if (shareDialog == null) {
               shareDialog = new ShareDialog(mActivity, R.style.Dialog);
               shareDialog.setOnItemClick(this);
               shareDialog.show();
           } else {
               shareDialog.show();
           }
      }
        }

    @Override
    public void onUserChange(User user) {
        if (user != null && !url.contains("userId=")) {
            if (url.contains("?")) {
                url = url + "&";
            } else {
                url = url + "?";
            }
            url = url + "token=" + UserProxy.getUser().getToken() + "&userId=" + UserProxy.getUser().getUserId();
            L.e(TAG, "url::" + url);
            webView.loadUrl(url);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        L.e(TAG,"onActivityResult");
        UMShareAPI.get(this).onActivityResult(requestCode, resultCode, data);
        if (requestCode == FILECHOOSER_RESULTCODE_FOR_ANDROID_5) {
            if (null == mUploadMessageForAndroid5)
                return;
            Uri result = (data == null || resultCode != RESULT_OK) ? null : data.getData();
            if (result != null) {
                L.e(TAG,"onActivityResult   emd11111111");
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{result});
            } else {
                mUploadMessageForAndroid5.onReceiveValue(new Uri[]{});
            }
            mUploadMessageForAndroid5 = null;
        }
        L.e(TAG,"onActivityResult   emd");
    }
}
